/*
 *    Copyright(c)2023-2024
 *    项目名称:hello-world
 *    文件名称:LoginServiceImpl.java
 *    Date:2023/12/3 上午12:03
 *    Author:赵士杰
 */

package com.hw.system.admin.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.hw.common.constant.Constants;
import com.hw.common.utils.bean.BeanCopyUtils;
import com.hw.common.utils.ip.UserAgentUtils;
import com.hw.common.utils.string.StringUtils;
import com.hw.exception.enums.ResCodeEnums;
import com.hw.exception.exception.CommonException;
import com.hw.system.admin.pojo.SysUser;
import com.hw.system.admin.service.ILoginService;
import com.hw.system.admin.service.ISysLoginLogService;
import com.hw.system.admin.service.ISysUserService;
import com.hw.system.admin.vo.LoginUserVo;
import com.hw.system.admin.vo.TokenInfoVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Project hello-world
 * @ClassName LoginServiceImpl
 * @Description //TODO
 * @Author Jie
 * @Date 2023/11/18 20:20
 */
@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysLoginLogService sysLoginLogService;

    @Override
    public TokenInfoVo login(LoginUserVo loginUserVo) {
        // TODO: 2023/11/16 验证码校验

        //校验参数
        if (StringUtils.isEmpty(loginUserVo.getUsername())) {
            throw new CommonException(ResCodeEnums.USERNAME_REQUIRED);
        }
        if (StringUtils.isEmpty(loginUserVo.getPassword())) {
            throw new CommonException(ResCodeEnums.PASSWORD_REQUIRED);
        }

        //验证用户名和密码是否正确
        SysUser user = sysUserService.getUserByUsername(loginUserVo.getUsername());

        if (ObjectUtils.isEmpty(user) || !loginUserVo.getPassword().equals(user.getPassword())) {
            throw new CommonException(ResCodeEnums.INVALID_USERNAME_OR_PASSWORD);
        }

        //用户名密码正确，登录成功，生成Token
        //将Token和用户信息存储到Redis中，并设置Token的过期时间
        String device = UserAgentUtils.getDeviceType();
        StpUtil.login(user.getUserId(), device);
        SaTokenInfo saTokenInfo = StpUtil.getTokenInfo();

        //更新用户登录信息
        sysUserService.updateUserLoginInfo(user.getUserId());

        //记录系统登录日志
        sysLoginLogService.recordLoginInfo(user.getUserId(), true, Constants.LOGIN_SUCCESS);

        //将Token返回给前端
        return BeanCopyUtils.copyBean(saTokenInfo, TokenInfoVo.class);
    }

}
